layui.use(['treeSelector', 'form', 'upload','laytpl','layedit','layer'], function(){
        var $ = layui.jquery,
        form = layui.form(),
        laytpl = layui.laytpl,
        layedit = layui.layedit,
        layer = layui.layer;
       	;
       	var categoryIds = $("input:hidden[name=categroy_id]").val() , focusId=[];
       	if(categoryIds != ''){
       		var focusId  = categoryIds.split(',');
       	}
        layui.treeSelector({elem:'#category-tree',type:'checkbox',only:true,focusId:focusId,categoryType:1});
        initProductTable();
        var productId = $("input:hidden[name=id]").val();
        if(productId != ''){
			reproduceProductPage(productId);
        }
        $(".add-base-attribute").click(function(){
        	initAttributeHtml('base');
        });
        $(".add-sku-attribute").click(function(){
			initAttributeHtml('sku');
        });
        $(".add-search-attribute").click(function(){
			initAttributeHtml('search');
        }); 
		form.on('checkbox(sku)', function(data){
			var skuData = createSkuData();
			createProductList(skuData.specData , skuData.specValueData);
		});
		form.on('select(shop)', function(data){
			//console.log(data.elem); //得到select原始DOM对象
			//console.log(data.value); //得到被选中的值
		  	changeBrand(data.value);
		});		
		layui.upload({
		    url: '/product/uploadProductImage/' //上传接口
		    ,ext: 'jpg|png|gif|jpeg'
		    ,success: function(res){ //上传成功后的回调
		      uploadPicCallback(res.data);
		    }
		});
		var editIndex = layedit.build('productContent',{
			height:500,
  			uploadImage:{url:'/product/uploadEditImage/'}
  		}); //建立编辑器
		form.verify({
			title: function(value){
				if(value.length <= 0){
					return '请填写商品名称';
				}
			},
			shop:function(value){
				if(value == ''){
					return '请选择供货商';
				}
			},
			categroy:function(value){
				if(value == 0){
					return '请选择分类';
				}
			},
			brand:function(value){
				if(value == ''){
					return '请选择品牌';
				}
			},
			content: function(value){
				layedit.sync(editIndex);
			},
			imgList: function(value){
				checkForm();
			}
		});
		form.on('submit(save)', function(data){
			//console.log(data.elem) //被执行事件的元素DOM对象，一般为button对象
			//console.log(data.form) //被执行提交的form对象，一般在存在form标签时才会返回
			//console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
			//return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
		});
		//var goodsImgs = [];
		var inputName = '';
		var picsBlock = '';

		$('#goodsBaseBody').on('click', '.add_goods_img', function(){
			var _this = $(this);
            var goodsImgs = [];
			inputName = _this.next('input').attr('name');
            var thumbnails = $('#thumbnails');
            var thumbnailsList = thumbnails.find('.pic img');
            var html = '';
            if(thumbnailsList.length > 0){
                for(var i = 0; i < thumbnailsList.length; i++){
                    var _path = $(thumbnailsList[i]).attr('alt');
                    var _src = $(thumbnailsList[i]).attr('src');
                    goodsImgs.push({ current: 0, img_path: _path, img_url: _src });
                }
                html = '<div class="pic">';
                for(var i = 0; i < goodsImgs.length; i++){
                    html += '<img src="'+ goodsImgs[i].img_url +'" class="pics" data-src="'+ goodsImgs[i].img_path +'">';
                }
                html += '</div>';
                picsBlock = layer.open({
                    type: 1,
                    title: '请选择相应图片',
                    skin: 'layui-layer-rim', //加上边框
                    area: ['545px', '315px'], //宽高
                    content: html
                });

            }else{
                layer.msg('请先上传产品图片');
                return false;
            }

            /*$.ajax({
                type:"get",
                url:"/product/ProductImages/" + productId,
                async:true,
                success:function(data){
                    if(data.success == true){
			 		var thumbnails = $('#thumbnails');
			 		var thumbnailsList = thumbnails.find('.pic img');
                    	if(thumbnailsList.length > 0){
							for(var i = 0; i < thumbnailsList.length; i++){
								var _path = $(thumbnailsList[i]).attr('alt');
								var _src = $(thumbnailsList[i]).attr('src');
                                goodsImgs.push({ current: 0, img_path: _path, img_url: _src });
							}
						}else{
                            layer.msg('请先上传产品图片');
                            return false;
						}
                    }
                    if(data.success == true && typeof(data.data) == 'object'){
                    	goodsImgs = data.data;
                    }
                    var  html = '<div class="pic">';
                    for(var i = 0; i < goodsImgs.length; i++){
                        html += '<img src="'+ goodsImgs[i].img_url +'" class="pics" data-src="'+ goodsImgs[i].img_path +'">';
                    }
                    html += '</div>';
                    picsBlock = layer.open({
                        type: 1,
                        title: '请选择相应图片',
                        skin: 'layui-layer-rim', //加上边框
                        area: ['545px', '315px'], //宽高
                        content: html
                    });
                },
                dataType:'json'
            });*/
		});

		$(document).on('click', 'img.pics', function(){
			var imgHost = 'http://img.dawangfu.com';
			var imgPath = $(this).attr('data-src');
			var inputArea = $('input[name="'+ inputName +'"]');
			var inputParent = inputArea.parents('td');
            inputParent.find('.add_goods_img').remove();
            inputArea.val(imgPath);
            $('<img src="'+ imgHost + imgPath +'" width="50" height="50" class="add_goods_img">').appendTo(inputParent);
            layer.close(picsBlock);
		});

});

function changeBrand(shopId){
	layui.use(['laytpl','form'], function(){
	        var $ = layui.jquery,
	        laytpl = layui.laytpl,
	        form = layui.form();
	        $.ajax({
	        	type:"get",
	        	url:"/product/shopBrand/" + shopId,
	        	async:true,
	        	success:function(data){
	        		if(data.success = true && typeof(data.data) == 'object'){
						var getTpl = brandTemplate.innerHTML;
						laytpl(getTpl).render(data.data, function(html){
						  $('select[name=brand]').html(html);
						  form.render();
						});	        			
				    }
	        	},
	        	dataType:'json'
	        });
	});	
}
function reproduceProductPage(productId){
	layui.use(['laytpl','tools' ,'form'], function(){
	        var $ = layui.jquery , 
	        laytpl = layui.laytpl,
	        form = layui.form();
			/**重现分类数据*/
			
			/**重现属性数据*/
			var attrbute = [];
			$.ajax({
				type:"get",
				url:"/product/productAttr/" + productId,
				async:true,
				success:function(data){
					if(data.success = true && typeof(data.data) == 'object'){
						attrbute = data.data;
						var type ;
						if(attrbute.hasOwnProperty('base') && attrbute.base.length > 0){
							$content = $content = $("#base-attribute-list");
							type = 'base';
							createAttributeForm(attrbute.base , $content , type);
						}
						if(attrbute.hasOwnProperty('search') && attrbute.search.length > 0){
							$content = $content = $("#search-attribute-list");
							type = 'search';
							createAttributeForm(attrbute.search , $content , type);
						}
						
						if(attrbute.hasOwnProperty('sku') && attrbute.sku.length > 0){
							$content = $content = $("#sku-attribute-list");
							type = 'sku';
							createAttributeForm(attrbute.sku , $content , type);
						}
						
						
					}
				},
				dataType:'json'
			});
			/**重现规格数据*/
			$.ajax({
				type:"get",
				url:"/product/productGoods/" + productId,
				async:true,
				success:function(data){
					if(data.success = true && typeof(data.data) == 'object'){
						specData = data.data.specData;
						productList = data.data.goodsList;
						var getTpl = goodsHeadTemplate.innerHTML;
						//创建规格标题
						laytpl(getTpl).render(specData, function(html){
						  	$('#goodsBaseHead').html(html);
						});
						//创建货品数据表格
						var getTpl = goodsRowTemplate.innerHTML;
						laytpl(getTpl).render(productList, function(html){
						  	$('#goodsBaseBody').html(html);
						});
						form.render();
						}
				},
				dataType:'json'
			});
			/**重现图片数据*/
			$.ajax({
				type:"get",
				url:"/product/ProductImages/" + productId,
				async:true,
				success:function(data){
					if(data.success = true && typeof(data.data) == 'object'){
						//创建货品数据表格
						var getTpl = picTemplate.innerHTML;
						$.each(data.data, function(i,e) {
							laytpl(getTpl).render(e, function(html){
							  	$('#thumbnails').append(html);
							});
						});
					}
				},
				dataType:'json'
			});			
			
	});		
}
/**
 * 初始化属性表单
 * @param {Object} type : 属性类型base 基本属性 search 搜索属性 sku 规格属性
 */
function initAttributeHtml(type){
	layui.use(['laytpl','tools' ,'form'], function(){
		 var $ = layui.jquery , 
	        tpl = layui.laytpl,
	        form = layui.form(),
			attribute_type ,attribute_type_name, category_ids , $content;
		switch(type){
			case 'base':
			  attribute_type = 1;
			  attribute_type_name = '基本属性';
			  $content = $("#base-attribute-list");
			  break;
			case 'search':
			  attribute_type = 2;
			  attribute_type_name = '检索属性';
			  $content = $("#search-attribute-list");
			  break;
			case 'sku':
			  attribute_type = 3;
			  attribute_type_name = '规格属性';
			  $content = $("#sku-attribute-list");
			  break;
		}
		category_ids = $("input:hidden[name=categroy_id]").val();
		if(category_ids == 0 || category_ids == ''){
			layer.msg('请先选择分类');
			return false;
		}
		var data = {attribute_type:attribute_type,category_ids:category_ids};
		var attribute_data = {title:attribute_type_name};
		$.ajax({
			type:"get",
			data:data,
			url:"/api/productAttribute/product_attribute_list/",
			async:true,
			dataType:'json',
			success:function(msg){
				if(msg.success = true){
					attribute_data.list = msg.data;
					//console.log(attribute_data);return;
					var getTpl = add_attribute_tpl.innerHTML;
					tpl(getTpl).render(attribute_data, function(html){
						layer.open({
						  type: 1,
						  title: '属性选择',
						  closeBtn: 1,
						  btn: ['保存'],
						  area: ['800px', '500px'],
						  shadeClose: true,
						  content: html,
						  cancel: function(){ 
						    //右上角关闭回调
						  },
						  yes: function(index, layero){
						    //按钮【按钮一】的回调
						    var $attribute_checked = $('#specs').find(':checkbox:checked'),
						    attribute = [];
						    $attribute_checked.each(function(index , item){
								attribute[index] = $.parseJSON($(this).val());			    		
							});	
							$.each(attribute, function(index,item) {
								attribute[index].values = layui.tools.parseJSON(item.value);
							});
						    createAttributeForm(attribute , $content , type);
						    layer.close(index);
						    if(attribute_type == 3){
						    	initProductTable();
						    }
						    
						  }
						});	
						form.render();
					});				 
				}
			}
		});
	});
}
function selSpect(_self,id){
	layui.use(['laytpl'], function(){
	        var $ = layui.jquery,
	        laytpl = layui.laytpl,
	        attribute_data,
	        attribute_value_data = {};
			_self.focus();
			//设置当前选中规格的样式
			$('ul>li').removeClass('current');
			$(_self).parent().parent().addClass('current');
			attribute_data = JSON.parse($(_self).val());
			attribute_value_data.list = JSON.parse(attribute_data.value);
			var getTpl = add_attribute_selected_tpl.innerHTML;
			laytpl(getTpl).render(attribute_value_data, function(html){
			  $('.goods_spec_box').html(html);
			});			
	});	
}
function createAttributeForm(attribute , $content , attribute_type){
	layui.use(['laytpl','tools' ,'form'], function(){
		var $ = layui.jquery ,
		laytpl = layui.laytpl,
		form = layui.form();
		if(attribute.length > 0){
			var getTpl = create_attribute_checked_tpl.innerHTML;
			var data = {
				'type':attribute_type,
				'list':attribute
			};
			laytpl(getTpl).render(data, function(html){
				$content.html(html);
				form.render();
			});
		}
	});	
			
}

//初始化货品表格
function initProductTable(){
	layui.use(['laytpl','tools' ,'form'], function(){
		var $ = layui.jquery ,
		laytpl = layui.laytpl,
		form = layui.form(),
		d = new Date();
		var defaultProductNo = String(d.getFullYear())  //默认商品编号
							+ String(d.getMonth() + 1)
							+ String(d.getDate())
							+ String(d.getHours())
							+ String(d.getMinutes())
							+ String(d.getSeconds())
							+ String(d.getMilliseconds());
		//console.log(attribute);return;
		var getTpl = goodsHeadTemplate.innerHTML;
		laytpl(getTpl).render({}, function(html){
			$('#goodsBaseHead').html(html);
		});
		var getTpl = goodsRowTemplate.innerHTML;
		laytpl(getTpl).render([[]], function(html){
			$('#goodsBaseBody').html(html);
		});
		$('input[name="_goods_no[0]"]').val(defaultProductNo);
		form.render();
	});	
}

function createSkuData(){
	var returnData =  {"specData":{},"specValueData":{}};
	layui.use(['tools'], function(){
        var $ = layui.jquery , 
        specValueData = {},
        specData      = {},
        $skuFromChecked = $("input:checkbox[name^='attr_sku']:checked");
        if($skuFromChecked.length == 0){
        		initProductTable();
        		return ;
        }
		$skuFromChecked.each(function()
		{
			var json = $.parseJSON($(this).attr('data-value'));
			if(!specValueData[json.id])
			{
				specData[json.id]      = json;
				specValueData[json.id] = [];
			}

			if($.inArray(json['value'],specValueData[json.id]) == -1)
			{
				specValueData[json.id].push($.parseJSON(json['value']));
			}
		});	        
        returnData =  {"specData":specData,"specValueData":specValueData};
	});
	return returnData;
}

function createProductList(specData,specValueData){
	layui.use(['laytpl','tools' ,'form'], function(){
        var $ = layui.jquery ,
			d = new Date(),
			laytpl = layui.laytpl,
	        form = layui.form();
		var defaultProductNo = String(d.getFullYear())  //默认商品编号
    						+ String(d.getMonth() + 1) 
    						+ String(d.getDate()) 
    						+ String(d.getHours())
    						+ String(d.getMinutes())
    						+ String(d.getSeconds())
    						+ String(d.getMilliseconds());        
		//生成货品的笛卡尔积
		var specMaxData = descartes(specValueData,specData);
		//从表单中获取默认商品数据
		var productJson = {};
		$('#goodsBaseBody tr:first').find('input[type="text"]').each(function(){
			productJson[this.name.replace(/^_(\w+)\[\d+\]/g,"$1")] = this.value;
		});
		//生成最终的货品数据
		var productList = [];
		for(var i = 0;i < specMaxData.length;i++)
		{
			var productItem = {};
			for(var index in productJson)
			{
				//自动组建货品号
				if(index == 'goods_no')
				{
					//值为空时设置默认货号
					if(productJson[index] == '')
					{
						productJson[index] = defaultProductNo;
					}
	
					if(productJson[index].match(/(?:\-\d*)$/) == null)
					{
						//正常货号生成
						productItem['goods_no'] = productJson[index]+'-'+(i+1);
					}
					else
					{
						//货号已经存在则替换
						productItem['goods_no'] = productJson[index].replace(/(?:\-\d*)$/,'-'+(i+1));
					}
				}
				else
				{
					productItem[index] = productJson[index];
				}
			}
			productItem['spec_array'] = specMaxData[i];
			productList.push(productItem);
		}
		var getTpl = goodsHeadTemplate.innerHTML;
		//创建规格标题
		laytpl(getTpl).render(specData, function(html){
		  	$('#goodsBaseHead').html(html);
		});
//			//创建货品数据表格
		var getTpl = goodsRowTemplate.innerHTML;
		laytpl(getTpl).render(productList, function(html){
		  	$('#goodsBaseBody').html(html);
		});
		form.render();	
		if($('#goodsBaseBody tr').length == 0)
		{
			initProductTable();
		}        
	});
	
}
//笛卡儿积组合
function descartes(list,specData){
	//parent上一级索引;count指针计数
	var point  = {};

	var result = [];
	var pIndex = null;
	var tempCount = 0;
	var temp   = [];

	//根据参数列生成指针对象
	for(var index in list)
	{
		if(typeof list[index] == 'object')
		{
			point[index] = {'parent':pIndex,'count':0}
			pIndex = index;
		}
	}
	//单维度数据结构直接返回
	if(pIndex == null)
	{
		return list;
	}
	//动态生成笛卡尔积
	while(true)
	{
		for(var index in list)
		{
			tempCount = point[index]['count'];
			temp.push({"id":specData[index].id,"type":specData[index].type,"name":specData[index].name,"value":list[index][tempCount]});
		}
		result.push(temp);
		temp = [];

		//检查指针最大值问题
		while(true)
		{
			if(point[index]['count']+1 >= list[index].length)
			{
				point[index]['count'] = 0;
				pIndex = point[index]['parent'];
				if(pIndex == null)
				{
					return result;
				}

				//赋值parent进行再次检查
				index = pIndex;
			}
			else
			{
				point[index]['count']++;
				break;
			}
		}
	}
}
/**
 * 删除一条sku
 * @param {Object} _self
 */
function delProduct(_self){
	layui.use(['jquery'], function(){
        var $ = layui.jquery;
		$(_self).parent().parent().remove();
		afreshSkuChecked();
		if($('#goodsBaseBody tr').length == 0)
		{
			initProductTable();
		}
	});
}
function afreshSkuChecked(){
	layui.use(['jquery','form'], function(){
        var $ = layui.jquery,
        form = layui.form(),
        $skuChecked = [],
        $skuUsed = [],
        skuUsedValue=[]
        ;
        $skuChecked = $('input:checkbox[name^=attr_sku_]:checked');
        $skuUsed = $("input:hidden[name^=_spec_array]");
        $skuUsed.each(function(){
        		skuUsedValue.push($(this).attr('data-id'));
        });
        skuUsedValue = skuUsedValue.unique();
		$skuChecked.each(function(){
			var currentDataId = $(this).attr('data-id');
			if($.inArray(currentDataId,skuUsedValue) == -1){
				$(this).attr("checked",false);
			}
		});
		form.render();
	});	
}
/**
 * 图片上传回调
 * 
 */
function uploadPicCallback(picJson){
	layui.use(['laytpl'], function(){
        var $ = layui.jquery,
        	laytpl = layui.laytpl
        ;
		//创建货品数据表格
		var getTpl = picTemplate.innerHTML;
		laytpl(getTpl).render(picJson, function(html){
		  	$('#thumbnails').append(html);
			//默认设置第一个为默认图片
			if($('#thumbnails img[name="picThumb"][class="current"]').length == 0)
			{
				$('#thumbnails img[name="picThumb"]:first').addClass('current');
			}		  	
		});	
	});
}
/**
 * 设置商品默认图片
 */
function defaultImage(_self){
	layui.use(['jquery'], function(){
        var $ = layui.jquery;
		$('#thumbnails img[name="picThumb"]').removeClass('current');
		$(_self).addClass('current');
	});
}
function moveBefore(_self){
	layui.use(['jquery'], function(){
        var $ = layui.jquery;
		$(_self).parents('.pic').insertBefore($(_self).parents('.pic').prev());
	});
}
function moveAfter(_self){
	layui.use(['jquery'], function(){
        var $ = layui.jquery;
		$(_self).parents('.pic').insertAfter($(_self).parents('.pic').next());
	});
}
function delImage(_self){
	layui.use(['jquery'], function(){
        var $ = layui.jquery;
		$(_self).parents('.pic').remove();
	});
}
function checkForm(){
	layui.use(['jquery'], function(){
        var $ = layui.jquery;
		//整理商品图片
		var goodsPhoto = [];
		$('#thumbnails img[name="picThumb"]').each(function(){
			goodsPhoto.push(this.alt);
		});
		if(goodsPhoto.length > 0)
		{
			$('input[name="_imgList"]').val(goodsPhoto.join(','));
			$('input[name="img"]').val($('#thumbnails img[name="picThumb"][class="current"]').attr('alt'));
		}
//		$("input:text[name^=attr_]").each(function(){
//			$(this).val('add' + ',' + $(this).attr('data-id') + ',' + $(this).val());
//		});
	});	
	return true;
}
Array.prototype.unique = function(){
	var n = {},r=[]; //n为hash表，r为临时数组
	for(var i = 0; i < this.length; i++) //遍历当前数组
	{
		if (!n[this[i]]) //如果hash表中没有当前项
		{
			n[this[i]] = true; //存入hash表
			r.push(this[i]); //把当前数组的当前项push到临时数组里面
		}
	}
	return r;
}